package com.predic8.membrane.servlet;

import com.predic8.membrane.servlet.embedded.ServletTransport;
import com.predic8.membrane.core.Router;
import org.springframework.web.context.support.XmlWebApplicationContext;

import javax.servlet.ServletContext;
import java.util.Collection;

public class RouteHelper {
    public static Router initializeRoutersFromSpringWebContext(XmlWebApplicationContext appCtx, final ServletContext ctx, String configLocation) {
        appCtx.setServletContext(ctx);
        appCtx.setConfigLocation(configLocation);
        appCtx.refresh();

        Collection<Router> routers = appCtx.getBeansOfType(Router.class).values();
        Router theOne = null;
        for (Router r : routers) {
            r.getResolverMap().addSchemaResolver(new FileSchemaWebAppResolver(ctx));
            if (r.getTransport() instanceof ServletTransport) {
                if (theOne != null)
                    throw new RuntimeException("Only one <router> may have a <servletTransport> defined.");
                theOne = r;
            }
        }

        appCtx.start();

        return theOne;
    }
}
